//发货单受理

interface IOrderAcceptViewModel extends IBaseViewModel<IOrderAcceptQueryTerms> {
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<orderList>;
    /**
     * 时间日期格式
     */
    dateFormat: "{format:'YYYY.MM.DD HH:mm'}";
    /**
     * 设置列表高度
     */
    heightA:number;
    /**
     * 选中的订单列表
     */
    orderIdInfoList: Array<selectOrderList>;
    /**
     * 订单状态下拉
     */
    orderStatusDropDown: ValueListItemResponse[];
    /**
     * 删除已选中订单
     */
    orderDel: (id: string) => void;
    /**
     * 发货单受理事件
     */
    orderAccept: () => void;
}

/**
 * 选中的订单列表
 */
interface selectOrderList {
    /**
     * 订单Id
     */
    orderId: string,
    /**
     * 订单状态
     */
    orderStatus: string,
    /**
     * 承运单id
     */
    carrierOrderId: string,
}

/**
 * 查询条件
 */
interface IOrderAcceptQueryTerms {
    /**
     * 订单编号
     */
    orderId: string;
    /**
     * 客户单位
     */
    clientName: string;
    /**
     *  线路地址
     */
    route: string;
    /**
     * 订单状态
     */
    orderStatus: string;
    /**
     * 发货起始时间
     */
    shipStartTime: string;
    /**
     * 发货结束时间
     */
    shipEndTime: string;
    /**
     * 发货地址
     */
    shipAddress: string;
    /**
     * 送货地址
     */
    deliverAddress: string;
    /**
     * 下单起始时间
     */
    placeOrderStartTime: string;
    /**
     * 下单结束时间
     */
    placeOrderEndTime: string;
}

class OrderAcceptController extends ListController<IOrderAcceptViewModel, IOrderAcceptQueryTerms>{

    gridApi: uiGrid.IGridApiOf<orderList>;
    /**
     * 选定选中，防止在翻页恢复选中效果时候误操作
     */
    lockSelect: boolean = false;

    orderBy: number = 0;
    asc: boolean = true;
    /**
     * 订单id
     */
    orderId:string;
    /**
     * 调度专员编号
     */
    dispatchOfficerId:string;

    constructor($scope: IOrderAcceptViewModel, private orderService: IorderService, private valueService: IValueService, private $ngBootbox: BootboxService,
        private employeeService: IEmployeeService, private $state: angular.ui.IStateService,private $timeout:ng.ITimeoutService,private $location:ng.ILocationService,private commonService:commonService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();
        this.dispatchOfficerId = JSON.parse(window.localStorage.getItem("loginData").toString()).id;  //调度专员
        this.$scope.orderIdInfoList = [];
        this.$scope.orderDel = (id)=>{this.orderDel(id,this.$scope.gridOptions.data)};
        this.$scope.orderAccept = this.orderAccept;
        this.$scope.$on("WildDog:Order11", this.onWilddogOrderEvent);
        this.$scope.queryTerms = {
            orderId: "",
            clientName: "",
            route: "",
            orderStatus: "",
            shipStartTime: "",
            shipEndTime: "",
            shipAddress: "",
            deliverAddress: "",
            placeOrderStartTime: "",
            placeOrderEndTime: "",
        }

        this.$scope.gridOptions = {
            multiSelect: true,
            enableFullRowSelection: true,
            enableSelectAll: false,
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "订单编号", field: 'orderId', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
                { displayName: "客户单位", field: 'clientName', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '12%' },
                { displayName: "发货地址", field: 'startAddress', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '12%' },
                { displayName: '送货地址', field: 'endAddress', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '12%' },
                { displayName: '发货时间', field: 'shipTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '7%' },
                { displayName: '货物名称', field: 'goodsName', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '货物数量', field: 'goodsNum', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '所需车长', field: 'carLength', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                { displayName: '下单时间', field: 'placeOrderTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '7%' },
                { displayName: '紧急程度', field: 'urgency', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '订单状态', field: 'orderStatus', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
                gridApi.core.notifyDataChange("options");
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                gridApi.selection.on.rowSelectionChanged(this.$scope, (row)=>{this.selectChange(row,this.$scope.gridOptions.data)});
            }
        }

        this.query();
        this.loadOrderStatusDropDown();

        $('#openStartTime').click(function () {
            $('#shipStartTime').datetimepicker('show');
        });
        $('#openEndTime').click(function () {
            $('#shipEndTime').datetimepicker('show');
        });
        $('#openPOrderStartTime').click(function () {
            $('#placeOrderStartTime').datetimepicker('show');
        });
        $('#openPOrderEndTime').click(function () {
            $('#placeOrderEndTime').datetimepicker('show');
        });
    }

    localHistory():void{
        super.localHistory(this.$state);
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }

    /**
     * 加载数据
     */
    loadData(queryTerms: IOrderAcceptQueryTerms, skip: number, count: number): void {
        if (queryTerms.orderStatus == "" || queryTerms.orderStatus == undefined || queryTerms.orderStatus == null) {
            status = "4,1" ;
        }
        else{
            status = queryTerms.orderStatus;
        }
        this.orderService.list(this.orderBy.toString(), this.asc, queryTerms.orderId, queryTerms.clientName, queryTerms.route, queryTerms.shipStartTime, queryTerms.shipEndTime,
            status, queryTerms.placeOrderStartTime, queryTerms.placeOrderEndTime, this.dispatchOfficerId, queryTerms.shipAddress, queryTerms.deliverAddress, "", skip, count).then(result => {
                this.$scope.gridOptions.totalItems = result.data.total;
                result.data.data.map((item,index)=>item.index = String(index+1));

                this.$scope.gridOptions.data = result.data.data;
                
                /**
                 * 设置列表高度
                 */
                this.$scope.heightA = (this.$scope.gridOptions.data.length*39) + 80;
                this.selectCheckBox(this.$scope.gridOptions.data);
                if (skip == 0) {
                    this.$scope.gridOptions.paginationCurrentPage = 1;
                }
                this.$scope.querying = false;
            }, error => {
                this.$scope.querying = false;
            });
           
           
    }

    /**
     * 监听野狗事件
     */
    onWilddogOrderEvent = (event: ng.IAngularEvent, data: any) => {
        this.query();
    }

    /**
     * 排序事件触发
     */
    sortChange = (grid: uiGrid.IGridInstanceOf<orderList>, sortColumns: Array<uiGrid.IGridColumnOf<orderList>>) => {
        if (sortColumns.length == 0) {
            this.query();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "orderId": {
                    this.orderBy = 1;
                } break;
                case "clientName": {
                    this.orderBy = 2;
                } break;
                case "startAddress": {
                    this.orderBy = 3;
                } break;
                case "endAddress": {
                    this.orderBy = 4;
                } break;
                case "shipTime": {
                    this.orderBy = 5;
                } break;
                case "goodsName": {
                    this.orderBy = 6;
                } break;
                case "goodsNum": {
                    this.orderBy = 7;
                } break;
                case "carLength": {
                    this.orderBy = 8;
                } break;
                case "placeOrderTime": {
                    this.orderBy = 9;
                } break;
                case "urgency": {
                    this.orderBy = 10;
                } break;
                case "orderStatus": {
                    this.orderBy = 11;
                } break;
            }
            this.asc = sortItem.sort.direction == "asc";
            this.query();
        }
    }

    /**
     * 选择事件
     */
    selectChange = (row: uiGrid.IGridRowOf<orderList>,data:string | orderList[]) => {
        if (this.lockSelect) {
            return;
        }
        //选中记录id，展现list
        if (row.isSelected) {
            this.orderId = row.entity.id;
            //判断状态是否一致;
            if (this.$scope.orderIdInfoList.length > 0) {
                if (this.$scope.orderIdInfoList[0].orderStatus == "退回派车" && this.isOrderListResponse(data)) {
                    this.$ngBootbox.alert("承运单只能选择一条");
                    this.lockSelect = true;
                    // this.gridApi.selection.unSelectRow(data[Number(row.entity.index) - (this.paginationOptions.currentPage - 1) * this.paginationOptions.pageSize - 1]),//取消选中行
                    
                    this.gridApi.selection.unSelectRow(data[Number(row.entity.index)-1]),//取消选中行
                    this.lockSelect = false;
                    return;
                };
                if (this.$scope.orderIdInfoList[0].orderStatus != "退回派车" && row.entity.orderStatus == "退回派车" && this.isOrderListResponse(data)) {
                    this.$ngBootbox.alert("订单状态不统一不能合并");
                    this.lockSelect = true;
                    // this.gridApi.selection.unSelectRow(data[Number(row.entity.index) - (this.paginationOptions.currentPage - 1) * this.paginationOptions.pageSize - 1])//取消选中行
                    this.gridApi.selection.unSelectRow(data[Number(row.entity.index)-1])//取消选中行
                    this.lockSelect = false;
                    return;
                }
            };
            //如果是退回派车状态，判断是否是多条,并选中
            if (row.entity.orderStatus == "退回派车" && this.isOrderListResponse(data)) {
                data.forEach((item, index) => {
                    this.lockSelect = true;
                    if (row.entity.carrierOrderId == item.carrierOrderId && this.isOrderListResponse(data)) {
                        this.gridApi.selection.selectRow(data[index]);
                        this.$scope.orderIdInfoList.push({
                            orderId: item.orderId,
                            orderStatus: "退回派车",
                            carrierOrderId: row.entity.carrierOrderId 
                        });
                    }
                    this.lockSelect = false;
                })
            }
            else {
                this.$scope.orderIdInfoList.push({
                    orderId: row.entity.orderId,
                    orderStatus: row.entity.orderStatus,
                    carrierOrderId: row.entity.carrierOrderId,
                });
            };
        }
        else if (row.isSelected == false) {
            if (row.entity.orderStatus == "退回派车" && this.isOrderListResponse(data)) {
                //承运单关联取消
                data.forEach((items, indexs) => {
                    if (row.entity.carrierOrderId == items.carrierOrderId) {
                        this.lockSelect = true;
                        this.$scope.orderIdInfoList.forEach((item, index) => {
                            for (var i = 0; i < data.length; i++) {
                                if(this.isOrderListResponse(data)){
                                    if (data[i].orderId == item.orderId && this.isOrderListResponse(data)) {
                                        this.gridApi.selection.unSelectRow(data[i]);
                                };
                                }
                            };
                        });
                        this.lockSelect = false;
                        this.$scope.orderIdInfoList = [];
                    };
                });
            }
            else {
                this.$scope.orderIdInfoList.forEach((item, index) => {
                    if (row.entity.orderId == item.orderId) {
                        this.$scope.orderIdInfoList.splice(index, 1);
                    }
                });
            }
        };
    }

    isOrderListResponse(response: string | orderList[]): response is orderList[] {
        return (<orderList[]>response).forEach !== undefined;
    }

    onQuery(): void {
        super.onQuery();
        this.selectChange;
    }

    //翻页后选中
    selectCheckBox = (data:string | orderList[])=>{
        if (this.$scope.orderIdInfoList.length <= 0) {
            return;
        }
        let itemCarrierId = this.$scope.orderIdInfoList[0].carrierOrderId;
        if(this.isOrderListResponse(data)){
            data.forEach((item, index) => {
                this.lockSelect = true;
                if (itemCarrierId == item.carrierOrderId && this.isOrderListResponse(data) && item.orderStatus =="退回派车") {
                    this.gridApi.selection.selectRow(data[index]);
                    this.$scope.orderIdInfoList.push({
                        orderId: item.orderId,
                        orderStatus: "退回派车",
                        carrierOrderId: itemCarrierId 
                    });
                }
                this.lockSelect = false;
            })
            var arr = this.commonService.unique(this.$scope.orderIdInfoList,"orderId");
           this.$scope.orderIdInfoList = arr;
        }

        this.$scope.orderIdInfoList.forEach((item, index) => {
             if (this.isOrderListResponse(data)) {
                 data.forEach((items,indexs)=>{
                     if(item.orderId === items.orderId){
                         this.$timeout(()=>{
                             if(this.isOrderListResponse(data)){
                                this.lockSelect = true;
                                this.gridApi.selection.selectRow(data[indexs]);
                                this.lockSelect = false;
                             }
                         });
                     }
                 });
             }
        });
    }

    /**
     * 订单状态下拉
     */
    loadOrderStatusDropDown(): void {
        this.$scope.orderStatusDropDown = this.valueService.getOrderStatusList().data;
    }

    /**
     * 发货单受理事件-合并单
     */
    orderAccept = () => {
        if (this.$scope.orderIdInfoList.length < 1) {
            this.$ngBootbox.alert("请选择一项");
            return;
        };
        if (this.$scope.orderIdInfoList.length > 1) {
            let stateArr = [];
            this.$scope.orderIdInfoList.forEach( (item, index) => {
                //console.log(this.$scope.orderIdInfoList);
                stateArr.push(item.orderId);
            });
            let carrierIds = this.$scope.orderIdInfoList[0].carrierOrderId;

            if (this.$scope.orderIdInfoList[0].orderStatus == "退回派车") {
                this.$state.go("app.order.orderAcceptBulk", { id: stateArr, carrierId: carrierIds, name: "Breakbulk", type: "退回派车" })
            } else if (this.$scope.orderIdInfoList[0].orderStatus == "派车中") {
                this.$state.go("app.order.orderAcceptBulk", { id: stateArr, name: "Breakbulk", type: "派车中" })
            };
        } 
        else {
            var carrierIds = this.$scope.orderIdInfoList[0].carrierOrderId;
            if (this.$scope.orderIdInfoList[0].orderStatus == "退回派车") {
                this.$state.go("app.order.orderAcceptDetail", { id: this.orderId, carrierId: carrierIds, name: "Accept", type: "退回派车" })
            } else if (this.$scope.orderIdInfoList[0].orderStatus == "派车中") {
                this.$state.go("app.order.orderAcceptDetail", { id: this.orderId, name: "Accept", type: "派车中" })
            };
        }
    }

    //删除选中订单
    orderDel = (arg,data:string | orderList[]) => {
        this.$scope.orderIdInfoList.forEach((item, index) => {
            if (arg === item.orderId) {
                this.$scope.orderIdInfoList.splice(index, 1);
                if (this.isOrderListResponse(data)) {
                    data.forEach((items, indexs) => {
                        if (item.orderId == items.orderId) {
                            if (this.isOrderListResponse(data)) {
                                this.gridApi.selection.unSelectRow(data[indexs]);   //取消选中行
                            }
                        }
                    });
                }
            };
        });
    }
}angular.module("tms").controller("orderAcceptController", ["$scope", "orderService", "valueService", "$ngBootbox", "employeeService","$state","$timeout","$location","commonService", OrderAcceptController]);